package com.qsign.sfrz_android.activity.home.ViewController;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.print_sdk.PrintUtil;
import com.google.gson.Gson;
import com.qsign.sfrz_android.R;
import com.qsign.sfrz_android.activity.home.Model.FuheModel;
import com.qsign.sfrz_android.activity.home.Model.PrintContract;
import com.qsign.sfrz_android.base.NewBaseActivity;
import com.qsign.sfrz_android.net.IServiceImpl;
import com.qsign.sfrz_android.net.RequestServiceImpl;
import com.qsign.sfrz_android.publicview.SimpleDialog;
import com.qsign.sfrz_android.utils.BaseUtil;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PiHaoActivity extends NewBaseActivity {
    @BindView(R.id.pihaoedit)
    EditText pihaoedit;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    QuickAdapter quickAdapter;
    List<FuheModel> fuheArray = new ArrayList<FuheModel>();
    PrintContract printContract;
    int pagenumber = 0;
    int number = 1000000001; // 初始化票据流水号 Initial bill serial number

    FuheModel whichitem=null;
    @Override
    protected void initTitle(TextView textView) {
        textView.setText("批号复核");
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_pihao;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recyclerview.setAdapter(quickAdapter);


        PrintUtil pUtil = PrintUtil.getClient();
        pUtil.setPrintEventListener(new PrintUtil.OnPrintEventListener() {
            @Override
            public void onPrintStatus(int state) {
                Log.e(TAG, "onPrintState: " + state);
                switch (state) {
                    case 0:
                        number += 1; // 流水号自加1 Serial number plus 1
                        pagenumber--;

                        Toast.makeText(PiHaoActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(PiHaoActivity.this, "没有打印纸了", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(PiHaoActivity.this, "打印失败", Toast.LENGTH_SHORT).show();
                        break;

                }
            }

            @Override
            public void onVersion(String version) {
                Log.e(TAG, "onVersion: " + version);
            }
        });

        printContract = new PrintContract(this, pUtil);
        printContract.printInit();


    }

    @OnClick({R.id.querybtn, R.id.backbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.querybtn:
                if (pihaoedit.getEditableText().toString().length() == 0) {
                    BaseUtil.ShowToast(this, "请输入批号");
                    return;
                }
                showWait();
                RequestServiceImpl.pihao_query(mMIPHandler, IServiceImpl.PIHAOQUERY, pihaoedit.getEditableText().toString());
                break;
            case R.id.backbtn:
                finish();
                break;
        }
    }

    public class QuickAdapter extends BaseQuickAdapter<FuheModel, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.pihao_list_item, fuheArray);
        }

        @Override
        protected BaseViewHolder createBaseViewHolder(View view) {
            AutoUtils.auto(view);
            return super.createBaseViewHolder(view);
        }

        @Override
        protected void convert(BaseViewHolder holder, final FuheModel item) {
            TextView indext = holder.getView(R.id.numberno);
            TextView SZXX = holder.getView(R.id.SZXX);
            TextView DIRECTION = holder.getView(R.id.DIRECTION);
            TextView YARNTYPE = holder.getView(R.id.YARNTYPE);
            TextView ORIPLACE = holder.getView(R.id.ORIPLACE);
            TextView BATCHNO = holder.getView(R.id.BATCHNO);
            RelativeLayout yllay= holder.getView(R.id.yllay);
            indext.setText(holder.getLayoutPosition() + 1 + "");
            SZXX.setText(item.getSZXX());
            DIRECTION.setText(item.getDIRECTION());
            YARNTYPE.setText(item.getYARNTYPE());
            ORIPLACE.setText(item.getORIPLACE());
            BATCHNO.setText(item.getBATCHNO());
            yllay.setVisibility(View.GONE);
            holder.getView(R.id.itemlay).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    whichitem=item;
                    showWait();
                    RequestServiceImpl.pihao_itemlist(mMIPHandler, IServiceImpl.PIHAOITEMLIST,item);
                }
            });

        }
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
        switch (requestType) {
            case IServiceImpl.PIHAOQUERY://根据条件查询
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                        fuheArray.clear();
                        if (dataarray != null && dataarray.size() > 0) {
                            Gson gson = new Gson();
                            for (Object o : dataarray) {
                                JSONObject jsonObject1 = (JSONObject) o;
                                FuheModel qrBean = gson.fromJson(jsonObject1.toJSONString(), FuheModel.class);
                                fuheArray.add(qrBean);
                            }
                        }
                        quickAdapter.notifyDataSetChanged();
                        quickAdapter.setEmptyView(R.layout.empty, (ViewGroup) recyclerview.getParent());
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("查询出错");
                        } else {
                            showSimpleDialog(msg);
                        }
                        pihaoedit.setText("");

                    }

                } catch (Exception e) {
                }
                break;

            case IServiceImpl.PIHAOITEMLIST://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                        if (dataarray != null && dataarray.size() > 0) {
                            Intent intent=new Intent(PiHaoActivity.this,PiHaoHistoryActivity.class);
                            Bundle bundel = new Bundle();
                            bundel.putSerializable("FuheModel", whichitem);
                            intent.putExtras(bundel);
                            startActivity(intent);
                        }else{//为空
                            showAlertAll(whichitem);
                        }

                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("查询出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
            break;
            case IServiceImpl.PIHAOPRINT://
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    if ("SUCCESS".equals(opt)) {
                        String TRAYCODE = jsonObject.getString("TRAYCODE");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < pagenumber; i++) {
                                    printContract.printBarcode(TRAYCODE, number);
                                }
                            }
                        }).start();
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("打印出错");
                        } else {
                            showSimpleDialog(msg);
                        }

                    }

                } catch (Exception e) {
                }
                break;

        }
    }

    private void showAlertAll(FuheModel item){
        View viewTips = LayoutInflater.from(this).inflate(R.layout.print_dialog, null);
        AutoUtils.auto(viewTips);
        Dialog alertDialog = BaseUtil.ShowMYDialog(this, viewTips, 340);
        alertDialog.show();
        LinearLayout zllay= viewTips.findViewById(R.id.zllay);
        zllay.setVisibility(View.GONE);
        TextView yuanliaotext = viewTips.findViewById(R.id.yuanliaotext);
        TextView changditext = viewTips.findViewById(R.id.changditext);
        TextView pihaotext = viewTips.findViewById(R.id.pihaotext);
        EditText numberedit = viewTips.findViewById(R.id.numberedit);
        EditText tuopanedit = viewTips.findViewById(R.id.tuopanedit);
        yuanliaotext.setText(item.getSZXX());
        changditext.setText(item.getORIPLACE());
        pihaotext.setText(item.getBATCHNO());

        viewTips.findViewById(R.id.printbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                closeKeyboard();
                if(tuopanedit.getEditableText().toString().length()==0){
                    BaseUtil.ShowToast(PiHaoActivity.this,"请输入托盘重量");
                }else if(numberedit.getEditableText().toString().length()==0){
                    BaseUtil.ShowToast(PiHaoActivity.this,"请输入打印数量");
                }else{
                    pagenumber=Integer.parseInt(numberedit.getEditableText().toString());
                    showWait();
                    RequestServiceImpl.pihaoprint(mMIPHandler, IServiceImpl.PIHAOPRINT,item,tuopanedit.getEditableText().toString());
                }

            }
        });
        viewTips.findViewById(R.id.cancellay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                closeKeyboard();
            }
        });
        numberedit.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showKeyboard(numberedit);
                } else {
                    closeKeyboard();
                }
            }
        });
        tuopanedit.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showKeyboard(tuopanedit);
                } else {
                    closeKeyboard();
                }
            }
        });
        tuopanedit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s==null){
                    return;
                }
                String temp=s.toString();
                int posDot=temp.indexOf(".");
                int index=tuopanedit.getSelectionStart();
                if(posDot>=0&&temp.length()-3>posDot){
                    s.delete(index-1,index);
                }
            }
        });

    }

    private void showSimpleDialog(String message) {
        SimpleDialog.show(this, message);
    }

}

